package com.sy.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sy.constant.JwtClaimsConstant;
import com.sy.constant.StatusConstant;
import com.sy.dto.*;
import com.sy.pojo.Employee;
import com.sy.pojo.User;
import com.sy.properties.JwtProperties;
import com.sy.result.Result;
import com.sy.service.CourseService;
import com.sy.service.UserService;
import com.sy.utils.HuYiCloudSMS;
import com.sy.utils.JwtUtil;
import com.sy.vo.CourseIndexVO;
import com.sy.vo.EmployeeLoginVO;
import com.sy.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户端-用户模块
 */
@Api(tags = "用户端-用户模块相关接口")
@RestController("commonUserController")
@RequestMapping("/user/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户端-查询手机号是否存在
     * @param phone
     * @return
     */
    @ApiOperation("用户端-查询手机号是否存在")
    @GetMapping("/doExistPhone")
    @ApiImplicitParams(
            @ApiImplicitParam(value = "要验证的用户名", name = "phone",
                    required = true, dataTypeClass = String.class)
    )
    public Result<String> doExistPhone(String phone) {
        //打印请求数据日志  select * from employee where phone = '';
        log.info("用户名为：{}", phone);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(queryWrapper);
        if (user == null){
            return Result.success();
        } else {
            return Result.error("手机号已存在");
        }
    }

    /**
     * 用户端-查询用户名是否存在
     * @param username
     * @return
     */
    @ApiOperation("用户端-查询用户名是否存在")
    @GetMapping("/doExistUsername")
    @ApiImplicitParams(
            @ApiImplicitParam(value = "要验证的用户名", name = "username",
                    required = true, dataTypeClass = String.class)
    )
    public Result<String> doExistUsername(String username) {
        //打印请求数据日志  select * from employee where username = '';
        log.info("用户名为：{}", username);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userService.getOne(queryWrapper);
        if (user == null){
            return Result.success();
        } else {
            return Result.error("用户名已存在");
        }
    }

    /**
     * 用户端-新增用户信息
     * @param userRegisterDTO
     * @return
     */
    @ApiOperation("用户端-新增用户信息")
    @PostMapping("/save")
    public Result save(@RequestBody UserRegisterDTO userRegisterDTO) {
        try {
            //打印请求数据日志
            log.info("新增员工信息：{}", userRegisterDTO);
            // 创建用户对象
            User user = new User();
            BeanUtils.copyProperties(userRegisterDTO, user);
            String password =
                    DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            // 对密码做加密操作
            user.setPassword(password);
            // 设置当前创建用户的时间
            user.setCreatetime(LocalDateTime.now());
            // 设置当前用户状态
            // user.setStatus(StatusConstant.ENABLE);
            // 新增员工信息
            userService.save(user);
        } catch (Exception e) {
            throw new RuntimeException("注册失败");
        }
        return Result.success();
    }

    /**
     * 用户端-登录功能(手机号 + 密码)
     * @param userLoginDTO
     * @return
     */
    @ApiOperation("用户端-登录功能")
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户端-登录功能：{}", userLoginDTO);
        User user = userService.login(userLoginDTO);

        // 登录成功后的用户信息保存token中
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getUid());
        // 秘钥
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        //把当前登录用户信息响应给前台，展示当前登录用户名
        UserLoginVO userLoginVO = new UserLoginVO();
        //把employee中的信息赋值到employeeLoginVO，返回的都是一些不敏感的信息
        BeanUtils.copyProperties(user, userLoginVO);
        userLoginVO.setToken(token);

        return Result.success(userLoginVO);
    }

    /**
     * 用户端-发送验证码
     * @param phone
     * @return
     */
    @ApiOperation("用户端-发送验证码")
    @GetMapping("/sendCode")
    public Result sendCode(String phone) {
        log.info("用户端-获取要发送验证码的手机号：{}", phone);
        // 发送验证码
        // String phoneCode = HuYiCloudSMS.sendSMS(phone);
        String phoneCode = "123456";
        // 将验证码保存到redis缓存中  13012341234_123456
        redisTemplate.opsForValue().set(phone + "_" + phoneCode, phoneCode, 5, TimeUnit.MINUTES);
        if (phoneCode != null){
            return Result.success();
        } else {
            return Result.success("验证码发送失败");
        }
    }

    /**
     * 用户端-登录功能(手机号 + 验证码)
     * @param userLoginDTO02 (手机号 + 用户输入的验证码)
     * @return
     */
    @ApiOperation("用户端-登录功能")
    @PostMapping("/login02")
    public Result login02(@RequestBody UserLoginDTO02 userLoginDTO02) {
        log.info("用户端-登录功能：{}", userLoginDTO02);
        // 获取redis中存储的验证码
        String redisCode = (String) redisTemplate.opsForValue().get(userLoginDTO02.getPhone() + "_" + userLoginDTO02.getCode());
        // 判断验证码是否一致
        if (redisCode != null && redisCode.equals(userLoginDTO02.getCode())){
            // 验证码正确
            User user = userService.login02(userLoginDTO02);

            // 登录成功后的用户信息保存token中
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID, user.getUid());
            // 秘钥
            String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                    jwtProperties.getUserTtl(),
                    claims);

            //把当前登录用户信息响应给前台，展示当前登录用户名
            UserLoginVO userLoginVO = new UserLoginVO();
            //把employee中的信息赋值到employeeLoginVO，返回的都是一些不敏感的信息
            BeanUtils.copyProperties(user, userLoginVO);
            userLoginVO.setToken(token);

            return Result.success(userLoginVO);

        } else{
            return Result.error("验证码错误...");
        }
    }

}
